package by.grsu.samusev.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.samusev.entity.Driver;
import by.grsu.samusev.table.DriverTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class DriverDao  extends AbstractDao<DriverTable, Driver> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1736204947894333469L;

	public DriverDao(String rootFolderPath) {
		super(rootFolderPath);
	
	}

	@Override
	public Long saveNew(final Driver newDriver) {
		Long nextId = getNextId();
				newDriver.setId( nextId);
				final DriverTable driverTable = deserializeFromXml();
				driverTable.getRows().add(newDriver);
			serializeToXml(driverTable);
			return nextId;
	}

	@Override
	public void update(final Driver entity) {
		final DriverTable driverTable = deserializeFromXml();
		for (final Driver row : driverTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
			row.setId(entity.getId());
				row.setName(entity.getName());
				row.setCarId(entity.getCarId());;
				break;
			}
		}
			serializeToXml(driverTable);

	}

	@Override
	public Driver get(final Serializable id) {
		final DriverTable driverTable = deserializeFromXml();
		for (final Driver row : driverTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Driver> getAll() {
		final DriverTable driverTable = deserializeFromXml();
		return driverTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
				final DriverTable driverTable = deserializeFromXml();
				Driver toBeDeleted = null;
				for (final Driver row : driverTable.getRows()) {
					if (row.getId().equals(id)) {
						toBeDeleted = row;
						break;
					}
				}
				driverTable.getRows().remove(toBeDeleted);
				serializeToXml(driverTable);
	}

	@Override
	protected Class<DriverTable> getTableClass() {
		return DriverTable.class;
	}

}
